import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pizza_test/const/const.dart';
import 'package:pizza_test/db/mydb.dart';
import 'package:pizza_test/model/chefmodel.dart';
import 'package:pizza_test/screen/view/foot_action.dart';
import 'view/chef_header.dart';

class HomeScreen extends StatefulWidget {

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  List<Chef> chefs = List.generate(7, (idx) => Chef(
      avatar: "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/13/13f5a6135bfaee7eb0bbd6cd3ae3ba9f8e1ce5c0_full.jpg",
      name: "Pizza Chef $idx", 
      speed: idx + 1,
      pizzas: <Pizza>[],
      iswork: false
    ));

  int pizzaNum = 0;

  List<ChefHeader> _createChefs() {
    List<ChefHeader> res = [];
    chefs.forEach((val){
      ChefHeader widget = ChefHeader(chef: val, stopAciton: (Chef sender){
        setState(() {
          chefs.forEach((val){
              if(val.name == sender.name) {
                val.iswork = !sender.iswork;
              }
            });
        });
      }, beginAction: (Chef sender){
        setState(() {
          chefs.forEach((val){
              if(val.name == sender.name) {
                val.iswork = !sender.iswork;
                val.newBegin();
              }
            });
        });
      },
      changePizzaToOtherAction: (Chef curr, String chefName, Pizza p){
        Chef current;
        Chef toChef;
        chefs.forEach((val){
          if(curr.name == val.name){
            current = val;
          }
          if(chefName == val.name) {
            toChef = val;
          }
        });

        setState(() {
          current.pizzas.remove(p);
          toChef.pizzas.add(p);
        });
      }
      ,finishPizzaion: _pizzafinishcallback);
      res.add(widget);
    });
    return res;
  }

  void _pizzafinishcallback(String name) async {
    var sql = MySQLiteDB();
    setState(() {
      chefs.forEach((val){
          if(val.name == name && val.pizzas.length > 0) {
            int pizzid = val.pizzas.first.pizzaId;
            sql.delete(pizzid);
            val.pizzas.removeAt(0);
          }
        });
    });
  }

  void _addPizza(int number) {
    setState(() {
      List<Pizza> pizzas = List.generate(number, (idx){
        return Pizza(pizzaId: idx + pizzaNum, isfinish: false, size: EpizzaSize.medium, toppings: []);
      });
      pizzaNum += number;
      var index = 0;
      int perNum = pizzas.length ~/ chefs.length;
      print(pizzas.sublist(1,2));
      var sql = MySQLiteDB();
      for(int i = 0;i < chefs.length; i++) {
        print("$index, $perNum");
        List<Pizza> temp = pizzas.sublist(index, perNum + index);
        print(temp);
        chefs[i].newAddPizzas(temp);
        index += perNum;
        sql.insertList(temp, i);
      }
      var temp = pizzas.sublist(index, pizzas.length);
      chefs.first.newAddPizzas(temp);
      sql.insertList(temp, 0);
    });
  }

  _queryFromDB() async {
    var sql = MySQLiteDB();
    List<Pizza> pizzas = await sql.query();
    pizzas.forEach((val){
      setState(() {
        pizzaNum = val.pizzaId + 1; // 更新最后一个🍕的id，不然数据库重复主键会崩溃
        chefs[val.chefId].pizzas.add(val);
      });
    });
    await sql.close();
  }

  void _closeAllAction(bool iswork)  {

    // Chef chef = Chef(speed: 1);
    // chef.newBegin();
    setState(() {
      chefs.forEach((val){
        val.iswork = iswork;
        if(iswork){
          val.newBegin();
        } else {
          val.newStop();
        }
        val.callback = _pizzafinishcallback;
      });
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _queryFromDB(); // 从数据库里面读取
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      body: Container(
        height: screenSize.height,
        width: screenSize.width,
        color: Colors.pinkAccent,
        child: Container(
          color: Colors.white,
          child: Container(
            child: Padding(
              padding: const EdgeInsets.all(2.0),
              child: Container(
                child: Column(
                  children: <Widget>[
                    Table(
                      border: TableBorder.all(color:Colors.grey, width: 1.0, style: BorderStyle.solid),
                      children:<TableRow> [
                        TableRow(
                          children: _createChefs(),
                        ),
                      ],
                    ),
                    Expanded(
                      child: FootActionView(chefs: chefs, 
                      addPizzaAction: _addPizza,
                      closeAllAction: _closeAllAction,
                      ),
                    )
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

